public class MyBlockingQueue {
    private int[] elem= new int[1000];
    private volatile int usedSize;
    private int front;
    private int rear;

    public MyBlockingQueue(){
        this.usedSize = 0;
        this.front = 0;
        this.rear = 0;
    }

    public void put(Integer val) throws InterruptedException {
        synchronized(this){
            //阻塞队列是否满
            while(this.usedSize==this.elem.length){
                this.wait();
            }
            this.elem[rear] = val;
            this.rear++;
            if(this.rear==this.elem.length){
                this.rear = 0;
            }
            this.usedSize++;
            this.notify();
        }
    }

    public Integer take() throws InterruptedException {
        int ret =0 ;
        synchronized(this){
            //判断队列是否为空进行阻塞,多次重复校验
            while(this.usedSize==0){
                this.wait();
            }
            ret = this.elem[front];
            this.front++;
            if(this.front==this.elem.length){
                this.front =0;
            }
            this.usedSize--;

            this.notify();
        }
        return ret;
    }

    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();

        Thread producer = new Thread(()->{
           int n =0;
           while(true){
               try {
                   queue.put(n);
                   System.out.println("生产了->" + n);
                   n++;
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        producer.start();
        Thread customer = new Thread(()->{
           while(true){
               try {
                   int value = queue.take();
                   System.out.println("消费了->" + value);
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        customer.start();

    }



}